package com.sp2.dev.test.equalsORhashcode;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: zhimingli
 * Date: 14-2-11
 * Time: 下午1:25
 * To change this template use File | Settings | File Templates.
 */
public class Apple {
    private String name;

    public Apple(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Apple)) {
            return false;
        }
        if (obj instanceof Apple) {
            return true;
        }
        return this.name == ((Apple) obj).name;
    }

    public static void main(String[] args) {
        Apple green = new Apple("green");
        Apple red = new Apple("red");
        Map<Apple, String> map = new HashMap<Apple, String>();
        map.put(green, "green");
        map.put(red, "red");
        //返回的是null
        //这个问题是因为”hashCode()”方法没有被重写。Java中equals()和hashCode()有一个契约：
        //1. 如果两个对象相等的话，它们的hash code必须相等；
        //2. 但如果两个对象的hash code相等的话，这两个对象不一定相等。
        System.out.println(map.get(new Apple("green")));
    }
}
